import React, {Component} from 'react'
import {
  Card,
  Select,
  Input,
  Button,
  Icon,
  Table,
  message,
  Modal
} from 'antd'

import LinkButton from '../../components/LinkButton'

import {reqProducts, reqSearchProducts, reqUpdateStatus, reqRemoveProduct } from '../../api'
import { PAGE_SIZE } from '../../utils/constants'
const {option} = Select
const { confirm } = Modal

// Product 的默认子路由组件
export default class ProductHome extends Component {
  state = {
    total: 0, // 商品的总数量
    products: [], // 商品数组
    isLoading: false, // 标识 显示/隐藏 loading
    searchName: '', // 搜索的关键字
    searchType: 'productName', // 根据那个字段搜索
  }

  // 初始化 table 的列数组
  initColumns = () => {
    this.columns = [
      {
        title: '商品名称',
        dataIndex: 'name',
      },
      {
        title: '商品描述',
        dataIndex: 'desc',
      },
      {
        title: '价格',
        dataIndex: 'price',
        render: price => '￥' + price
      },
      {
        width: 100,
        title: '状态',
        // dataIndex: 'status',
        render: product => {
          const { status, _id } = product
          const newStatus = status === 1 ? 2 : 1
          return (
            <span>
              <Button
                type='primary'
                onClick={() => this.updateStatus(_id, newStatus)}>
                { status === 1 ? '下架' : '上架' }
              </Button>
              <span>{ status === 1 ? '在售' : '已下架' }</span>
            </span>
          )
        }
      },
      {
        width: 100,
        title: '操作',
        // dataIndex: 'product',
        render: product => (
          <span>
            {/* 将 product 对象传递给目标路由组件 */}
            <LinkButton onClick={() => this.props.history.push('/product/detail', {product})}>详情</LinkButton>
            <LinkButton onClick={() => this.props.history.push('/product/addupdate', product)}>修改</LinkButton>
            <LinkButton style={{color: '#ff4d4feb'}} onClick={() => this.removeProduct(product._id)}>删除</LinkButton>
          </span>
        )
      },
    ]
  }

  // 获取指定页码的列表数据显示
  getProducts = async (pageNum) => {
    this.pageNum = pageNum // 保存 pageNum, 让其他方法看见
    this.setState({ isLoading: true }) // 显示 loading

    const { searchName, searchType } = this.state
    let result
    // 如果搜索关键字有值, 说明我们要做搜索分页
    if (searchName) {
      result = await reqSearchProducts({pageNum, pageSize: PAGE_SIZE, searchName, searchType})
    } else {
      result = await reqProducts(pageNum, PAGE_SIZE)
    }

    this.setState({ isLoading: false }) // 隐藏 loading
    if (result.status === 0) {
      // 去出分页数据, 更新分页, 显示数据
      const { total, list } = result.data
      this.setState({
        total,
        products: list
      })
    }
  }

  // 根据 id 删除产品
  removeProduct = (productId) => {
    console.log(productId)
    // 1 显示对话框提示
    confirm({
      title: `确认删除此产品吗?`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        // 2. 准备数据, 发送请求删除分类
        const result = await reqRemoveProduct(productId)
        console.log(result)
        // 3. 重新显示当前分类数据
        if (result.status === 0) {
          // 提示删除成功
          message.success('删除产品成功')
          this.getProducts(this.pageNum)
        } else {
          message.error('删除产品成功')
        }
      },
      onCancel() {
        // console.log('Cancel')
      },
    })
  }

  // 更新指定商品的状态
  updateStatus = async (productId, status) => {
    const result = await reqUpdateStatus({ productId, status })
    if (result.status === 0) {
      message.success('更新商品成功')
      this.getProducts(this.pageNum)
    }
  }

  UNSAFE_componentWillMount () {
    this.initColumns()
  }

  componentDidMount () {
    this.getProducts(1)
  }

  render() {
    const { products, total, isLoading, searchName, searchType } = this.state

    const title = (
      <span>
        <Select
          value={searchType}
          style={{width: 150}}
          onChange={value => this.setState({searchType: value})}>
          <option value="productName">按名称搜索</option>
          <option value="productDesc">按描述搜索</option>
        </Select>
        <Input
          placeholder='请输入关键字'
          style={{width: 150, margin: '0 15px'}}
          value={searchName}
          onChange={e => this.setState({searchName: e.target.value})}
        />
        <Button type='primary' onClick={() => this.getProducts(1)}>搜索</Button>
      </span>
    )

    const extra = (
      <Button type='primary' onClick={() => this.props.history.push('/product/addupdate')}>
        <Icon type='plus'/>
        添加商品
      </Button>
    )

    return (
      <Card title={title} extra={extra}>
        <Table
          currend={this.pageNum}
          rowKey='_id'
          bordered={true}
          loading={isLoading}
          dataSource={products}
          columns={this.columns}
          pagination={{
            total,
            defaultPageSize: PAGE_SIZE,
            showQuickJumper: true,
            onChange: this.getProducts }}
        />
      </Card>
    )
  }
}
